<!DOCTYPE html>


  <html class="dark page-post">


<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="utf-8">
  
  <title>shell入门 | Poetry&#39;s Blog</title>

  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

  
    <meta name="keywords" content="Linux,Shell,">
  

  <meta name="description" content="最近使用shell比较多，这里记录一下  一、初识shell1.1 Shell 环境 Linux 的 Shell 种类众多，常见的有   /usr/bin/sh或/bin/sh /bin/bash C Shell（/usr/bin/csh） K Shell（/usr/bin/ksh） Shell for Root（/sbin/sh）   Bash 在日常工作中被广泛使用。同时，Bash 也是大多">
<meta name="keywords" content="Linux,Shell">
<meta property="og:type" content="article">
<meta property="og:title" content="shell入门">
<meta property="og:url" content="http://blog.poetries.top/2018/12/24/shell/index.html">
<meta property="og:site_name" content="Poetry&#39;s Blog">
<meta property="og:description" content="最近使用shell比较多，这里记录一下  一、初识shell1.1 Shell 环境 Linux 的 Shell 种类众多，常见的有   /usr/bin/sh或/bin/sh /bin/bash C Shell（/usr/bin/csh） K Shell（/usr/bin/ksh） Shell for Root（/sbin/sh）   Bash 在日常工作中被广泛使用。同时，Bash 也是大多">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2020-08-15T04:25:31.934Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="shell入门">
<meta name="twitter:description" content="最近使用shell比较多，这里记录一下  一、初识shell1.1 Shell 环境 Linux 的 Shell 种类众多，常见的有   /usr/bin/sh或/bin/sh /bin/bash C Shell（/usr/bin/csh） K Shell（/usr/bin/ksh） Shell for Root（/sbin/sh）   Bash 在日常工作中被广泛使用。同时，Bash 也是大多">

  

  
    <link rel="icon" href="/favicon.ico">
  

  <link href="/css/styles.css?v=c114cbeddx" rel="stylesheet">
<link href="/css/other.css?v=c114cbeddx" rel="stylesheet">


  
    <link rel="stylesheet" href="/css/personal-style.css">
  

  

  
  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?40b1f89aa80f2527b3db779c6898c879";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>


  
  <script type="text/javascript">
	(function(){
	    var bp = document.createElement('script');
	    var curProtocol = window.location.protocol.split(':')[0];
	    if (curProtocol === 'https') {
	        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
	    }
	    else {
	        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
	    }
	    var s = document.getElementsByTagName("script")[0];
	    s.parentNode.insertBefore(bp, s);
	})();
  </script>



  
    <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <link rel="stylesheet" href="//cdn.bootcss.com/font-awesome/4.3.0/css/font-awesome.min.css">
  

  <!-- 聊天系统 -->
  
    
   <link type="text/css" rel="stylesheet" href="/renxi/default.css">
   <style>
      #modal {
        position: static !important;
      }
      .filter {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        background: #fe5757;
        animation: colorChange 30s ease-in-out infinite;
        animation-fill-mode: both;
        mix-blend-mode: overlay;
      }
  
      @keyframes colorChange {
        0%, 100% {
            opacity: 0;
        }
        50% {
            opacity: .9;
        }
      }
   </style>
</head>
</html>
<body>
  
  
    <span id="toolbox-mobile" class="toolbox-mobile">导航</span>
  

  <div class="post-header CENTER">
   
  <div class="toolbox">
    <a class="toolbox-entry" href="/">
      <span class="toolbox-entry-text">导航</span>
      <i class="icon-angle-down"></i>
      <i class="icon-home"></i>
    </a>
    <ul class="list-toolbox">
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/archives/"
            rel="noopener noreferrer"
            target="_self"
            >
            博客
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/categories/"
            rel="noopener noreferrer"
            target="_self"
            >
            分类
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/tags/"
            rel="noopener noreferrer"
            target="_self"
            >
            标签
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/search/"
            rel="noopener noreferrer"
            target="_self"
            >
            搜索
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/link/"
            rel="noopener noreferrer"
            target="_self"
            >
            友链
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/about/"
            rel="noopener noreferrer"
            target="_self"
            >
            关于
          </a>
        </li>
      
    </ul>
  </div>


</div>


  <div id="toc" class="toc-article">
    <strong class="toc-title">文章目录<i class="iconfont toc-title" style="display:inline-block;color:#87998d;width:20px;height:20px;">&#xf004b;</i></strong>
    <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#一、初识shell"><span class="toc-text">一、初识shell</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-1-Shell-环境"><span class="toc-text">1.1 Shell 环境</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-2-运行-Shell-脚本有两种方法"><span class="toc-text">1.2 运行 Shell 脚本有两种方法</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#二、shell变量"><span class="toc-text">二、shell变量</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#2-1-使用变量"><span class="toc-text">2.1 使用变量</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-2-只读变量"><span class="toc-text">2.2 只读变量</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-3-删除变量"><span class="toc-text">2.3 删除变量</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-4-变量类型"><span class="toc-text">2.4 变量类型</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-5-Shell-字符串"><span class="toc-text">2.5 Shell 字符串</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-6-拼接字符串"><span class="toc-text">2.6 拼接字符串</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-7-获取字符串长度"><span class="toc-text">2.7 获取字符串长度</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-8-提取子字符串"><span class="toc-text">2.8 提取子字符串</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-9-Shell-数组"><span class="toc-text">2.9 Shell 数组</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-10-定义数组"><span class="toc-text">2.10 定义数组</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-11-读取数组"><span class="toc-text">2.11 读取数组</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-12-获取数组的长度"><span class="toc-text">2.12 获取数组的长度</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-13-Shell-注释"><span class="toc-text">2.13 Shell 注释</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#三、shell传递参数"><span class="toc-text">三、shell传递参数</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#四、数组"><span class="toc-text">四、数组</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#4-1-读取数组"><span class="toc-text">4.1 读取数组</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-2-获取数组中的所有元素"><span class="toc-text">4.2 获取数组中的所有元素</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-3-获取数组的长度"><span class="toc-text">4.3 获取数组的长度</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#五、基本运算符"><span class="toc-text">五、基本运算符</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#5-1-算术运算符"><span class="toc-text">5.1 算术运算符</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-2-关系运算符"><span class="toc-text">5.2 关系运算符</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-3-布尔运算符"><span class="toc-text">5.3 布尔运算符</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-4-逻辑运算符"><span class="toc-text">5.4 逻辑运算符</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-5-字符串运算符"><span class="toc-text">5.5 字符串运算符</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-6-文件测试运算符"><span class="toc-text">5.6 文件测试运算符</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#六、echo用法"><span class="toc-text">六、echo用法</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#6-1-显示普通字符串"><span class="toc-text">6.1 显示普通字符串:</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6-2-显示转义字符"><span class="toc-text">6.2 显示转义字符</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6-3-显示变量"><span class="toc-text">6.3 显示变量</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6-4-显示换行"><span class="toc-text">6.4 显示换行</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6-5-显示不换行"><span class="toc-text">6.5 显示不换行</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6-6-显示结果定向至文件"><span class="toc-text">6.6 显示结果定向至文件</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6-7-显示命令执行结果"><span class="toc-text">6.7 显示命令执行结果</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#七、printf用法"><span class="toc-text">七、printf用法</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#八、test命令"><span class="toc-text">八、test命令</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#8-1-数值测试"><span class="toc-text">8.1 数值测试</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#8-2-字符串测试"><span class="toc-text">8.2 字符串测试</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#8-3-文件测试"><span class="toc-text">8.3 文件测试</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#九、流程控制if-while-case"><span class="toc-text">九、流程控制if/while/case</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#9-1-if"><span class="toc-text">9.1 if</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#9-2-if-else"><span class="toc-text">9.2 if else</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#9-3-if-else-if-else"><span class="toc-text">9.3 if else-if else</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#9-4-for-循环"><span class="toc-text">9.4 for 循环</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#9-5-while-语句"><span class="toc-text">9.5 while 语句</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#9-6-until-循环"><span class="toc-text">9.6 until 循环</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#9-7-case"><span class="toc-text">9.7 case</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#9-8-跳出循环"><span class="toc-text">9.8 跳出循环</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#9-9-continue"><span class="toc-text">9.9 continue</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#十、函数"><span class="toc-text">十、函数</span></a></li></ol>
  </div>
  




<div class="content content-post CENTER">
   <!-- canvas 彩带 -->
<canvas id="evanyou" width="1302" height="678" style="position: fixed;width: 100%;height: 100%;top: 0;left:0;z-index:-1;"></canvas>

<article id="post-shell" class="article article-type-post" itemprop="blogPost">
  <header class="article-header" style="position:relative;">
    <h1 class="post-title">shell入门</h1>

    <div class="article-meta">
      <span>
        <i class="icon-calendar"></i>
        <span>2018.12.24</span>
      </span>

      
        <span class="article-author">
          <i class="icon-user"></i>
          <span>Poetry</span>
        </span>
      

      
  <span class="article-category">
    <i class="icon-list"></i>
    <a class="article-category-link" href="/categories/Back-end/">Back-end</a>
  </span>



      

      
      <i class="fa fa-eye"></i> 
        <span id="busuanzi_container_page_pv">
           &nbsp热度 <span id="busuanzi_value_page_pv">
           <i class="fa fa-spinner fa-spin"></i></span>℃
        </span>
      
      
       
          <span class="post-count">
            <i class="fa fa-file-word-o"></i>&nbsp
            <span>字数统计 7.3k字</span>
          </span>

          <span class="post-count">
            <i class="fa fa-columns"></i>&nbsp
            <span>阅读时长 29分</span>
          </span>
      
      
    </div>

    <i class="iconfont" id="toc-eye" style="display:inline-block;color:#b36619;position:absolute;top:0;right:0;cursor:pointer;
    font-size: 24px;">&#xe61c;</i>

  </header>

  <div class="article-content">
    
      <div id="container">
        <blockquote>
<p>最近使用<code>shell</code>比较多，这里记录一下</p>
</blockquote>
<h2 id="一、初识shell"><a href="#一、初识shell" class="headerlink" title="一、初识shell"></a>一、初识shell</h2><h3 id="1-1-Shell-环境"><a href="#1-1-Shell-环境" class="headerlink" title="1.1 Shell 环境"></a>1.1 Shell 环境</h3><blockquote>
<p><code>Linux</code> 的 <code>Shell</code> 种类众多，常见的有</p>
</blockquote>
<ul>
<li><code>/usr/bin/sh</code>或<code>/bin/sh</code></li>
<li><code>/bin/bash</code></li>
<li><code>C Shell（/usr/bin/csh）</code></li>
<li><code>K Shell（/usr/bin/ksh）</code></li>
<li><code>Shell for Root（/sbin/sh）</code></li>
</ul>
<blockquote>
<p><code>Bash</code> 在日常工作中被广泛使用。同时，<code>Bash</code> 也是大多数<code>Linux</code> 系统默认的 <code>Shell</code></p>
</blockquote>
<ul>
<li>打开文本编辑器(可以使用 <code>vi/vim</code> 命令来创建文件)，新建一个文件 <code>test.sh</code>，扩展名为 <code>sh</code>（<code>sh</code>代表<code>shell</code>），扩展名并不影响脚本执行，见名知意就好</li>
</ul>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="meta">#!/bin/bash</span></span><br><span class="line"><span class="built_in">echo</span> <span class="string">"Hello World !"</span></span><br></pre></td></tr></table></figure>
<ul>
<li><code>#!</code> 是一个约定的标记，它告诉系统这个脚本需要什么解释器来执行，即使用哪一种 <code>Shell</code></li>
<li><code>echo</code> 命令用于向窗口输出文本</li>
</ul>
<h3 id="1-2-运行-Shell-脚本有两种方法"><a href="#1-2-运行-Shell-脚本有两种方法" class="headerlink" title="1.2 运行 Shell 脚本有两种方法"></a>1.2 运行 Shell 脚本有两种方法</h3><p><strong>作为可执行程序</strong></p>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">chmod +x ./test.sh  #使脚本具有执行权限</span><br><span class="line">./test.sh  #执行脚本</span><br></pre></td></tr></table></figure>
<blockquote>
<p>注意，一定要写成 <code>./test.sh</code>，而不是 <code>test.sh</code>，运行其它二进制的程序也一样，直接写 <code>test.sh</code>，<code>linux</code> 系统会去 <code>PATH</code> 里寻找有没有叫 <code>test.sh</code> 的，而只有 <code>/bin</code>, <code>/sbin,</code> <code>/usr/bin</code>，<code>/usr/sbin</code> 等在 <code>PATH</code> 里，你的当前目录通常不在 <code>PATH</code> 里，所以写成 <code>test.sh</code> 是会找不到命令的，<strong>要用 ./test.sh 告诉系统说，就在当前目录找</strong></p>
</blockquote>
<p><strong>作为解释器参数</strong></p>
<ul>
<li>这种运行方式是，直接运行解释器，其参数就是 <code>shell</code> 脚本的文件名</li>
</ul>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">/bin/sh test.sh</span><br><span class="line">/bin/php test.php</span><br></pre></td></tr></table></figure>
<ul>
<li>这种方式运行的脚本，不需要在第一行指定解释器信息，写了也没用</li>
</ul>
<h2 id="二、shell变量"><a href="#二、shell变量" class="headerlink" title="二、shell变量"></a>二、shell变量</h2><ul>
<li>定义变量时，变量名不加美元符号</li>
<li>注意，变量名和等号之间不能有空格</li>
<li>命名只能使用英文字母，数字和下划线，首个字符不能以数字开头</li>
<li><code>中间不能有空格</code>，可以使用下划线（<code>_</code>）</li>
<li>不能使用标点符号</li>
<li>不能使用<code>bash</code>里的关键字（可用<code>help</code>命令查看保留关键字）</li>
</ul>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">your_name=<span class="string">"poetries"</span> <span class="comment">#中间不能有空格</span></span><br></pre></td></tr></table></figure>
<ul>
<li>有效的 <code>Shell</code> 变量名示例如下</li>
</ul>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">RUNOOB</span><br><span class="line">LD_LIBRARY_PATH</span><br><span class="line">_var</span><br><span class="line">var2</span><br></pre></td></tr></table></figure>
<h3 id="2-1-使用变量"><a href="#2-1-使用变量" class="headerlink" title="2.1 使用变量"></a>2.1 使用变量</h3><ul>
<li>使用一个定义过的变量，只要在变量名前面加美元符号即可</li>
</ul>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">your_name=<span class="string">"poetries"</span></span><br><span class="line"><span class="built_in">echo</span> <span class="variable">$your_name</span></span><br><span class="line"><span class="built_in">echo</span> <span class="variable">$&#123;your_name&#125;</span></span><br></pre></td></tr></table></figure>
<ul>
<li>变量名外面的花括号是可选的，加不加都行，加花括号是为了帮助解释器识别变量的边界，比如下面这种情况</li>
<li>如果不给<code>skill</code>变量加花括号，写成<code>echo &quot;I am good at $skillScript&quot;</code>，解释器就会把<code>$skillScript</code>当成一个变量（其值为空），代码执行结果就不是我们期望的样子了</li>
<li>推荐给所有变量加上花括号，这是个好的编程习惯</li>
</ul>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">for skill in Ada Coffe Action Java; do</span><br><span class="line">    echo &quot;I am good at $&#123;skill&#125;Script&quot;</span><br><span class="line">done</span><br></pre></td></tr></table></figure>
<ul>
<li>已定义的变量，可以被重新定义，如：</li>
</ul>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">your_name=<span class="string">"tom"</span></span><br><span class="line"><span class="built_in">echo</span> <span class="variable">$your_name</span></span><br><span class="line">your_name=<span class="string">"alibaba"</span></span><br><span class="line"><span class="built_in">echo</span> <span class="variable">$your_name</span></span><br></pre></td></tr></table></figure>
<h3 id="2-2-只读变量"><a href="#2-2-只读变量" class="headerlink" title="2.2 只读变量"></a>2.2 只读变量</h3><ul>
<li>使用 <code>readonly</code> 命令可以将变量定义为只读变量，只读变量的值不能被改变</li>
<li>下面的例子尝试更改只读变量，结果报错</li>
</ul>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="meta">#!/bin/bash</span></span><br><span class="line">myUrl=<span class="string">"http://www.w3cschool.cc"</span></span><br><span class="line"><span class="built_in">readonly</span> myUrl</span><br><span class="line">myUrl=<span class="string">"http://www.runoob.com"</span></span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">/bin/sh: NAME: This variable is read only.</span><br></pre></td></tr></table></figure>
<h3 id="2-3-删除变量"><a href="#2-3-删除变量" class="headerlink" title="2.3 删除变量"></a>2.3 删除变量</h3><ul>
<li>使用 <code>unset</code> 命令可以删除变量。</li>
<li>语法 <code>unset variable_name</code></li>
<li>变量被删除后不能再次使用。<code>unset</code> 命令不能删除只读变量</li>
</ul>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="meta">#!/bin/sh</span></span><br><span class="line">myUrl=<span class="string">"http://www.runoob.com"</span></span><br><span class="line"><span class="built_in">unset</span> myUrl</span><br><span class="line"><span class="built_in">echo</span> <span class="variable">$myUrl</span></span><br></pre></td></tr></table></figure>
<h3 id="2-4-变量类型"><a href="#2-4-变量类型" class="headerlink" title="2.4 变量类型"></a>2.4 变量类型</h3><p><strong>运行shell时，会同时存在三种变量</strong></p>
<ul>
<li><strong>局部变</strong>量 局部变量在脚本或命令中定义，仅在当前<code>shell</code>实例中有效，其他<code>shell</code>启动的程序不能访问局部变量</li>
<li><strong>环境变量</strong> 所有的程序，包括<code>shell</code>启动的程序，都能访问环境变量，有些程序需要环境变量来保证其正常运行。必要的时候<code>shell</code>脚本也可以定义环境变量</li>
<li><strong><code>shell</code>变量</strong> <code>shell</code>变量是由<code>shell</code>程序设置的特殊变量。<code>shell</code>变量中有一部分是环境变量，有一部分是局部变量，这些变量保证了<code>shell</code>的正常运行</li>
</ul>
<h3 id="2-5-Shell-字符串"><a href="#2-5-Shell-字符串" class="headerlink" title="2.5 Shell 字符串"></a>2.5 Shell 字符串</h3><ul>
<li>字符串是<code>shell</code>编程中最常用最有用的数据类型（除了数字和字符串，也没啥其它类型好用了），字符串可以用单引号，也可以用双引号，也可以不用引号。单双引号的区别跟<code>PHP</code>类似。</li>
</ul>
<p><strong>单引号</strong></p>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">str=&apos;this is a string&apos;</span><br></pre></td></tr></table></figure>
<ul>
<li>单引号里的任何字符都会原样输出，单引号字符串中的变量是无效的</li>
<li>单引号字串中不能出现单引号（对单引号使用转义符后也不行）</li>
</ul>
<p><strong>双引号</strong></p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">author=<span class="string">'poetries'</span></span><br><span class="line"><span class="built_in">echo</span> <span class="string">"hello,I'm <span class="variable">$&#123;author&#125;</span>"</span></span><br></pre></td></tr></table></figure>
<ul>
<li>双引号里可以有变量</li>
<li>双引号里可以出现转义字符</li>
</ul>
<h3 id="2-6-拼接字符串"><a href="#2-6-拼接字符串" class="headerlink" title="2.6 拼接字符串"></a>2.6 拼接字符串</h3><figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">your_name=<span class="string">"poetries"</span></span><br><span class="line">greeting=<span class="string">"hello, "</span><span class="variable">$your_name</span><span class="string">" !"</span></span><br><span class="line">greeting_1=<span class="string">"hello, <span class="variable">$&#123;your_name&#125;</span> !"</span></span><br><span class="line"><span class="built_in">echo</span> <span class="variable">$greeting</span> <span class="variable">$greeting_1</span></span><br></pre></td></tr></table></figure>
<h3 id="2-7-获取字符串长度"><a href="#2-7-获取字符串长度" class="headerlink" title="2.7 获取字符串长度"></a>2.7 获取字符串长度</h3><figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">author=<span class="string">'poetries'</span></span><br><span class="line"><span class="built_in">echo</span> <span class="string">"length:<span class="variable">$&#123;#author&#125;</span>"</span> <span class="comment"># length:8</span></span><br></pre></td></tr></table></figure>
<h3 id="2-8-提取子字符串"><a href="#2-8-提取子字符串" class="headerlink" title="2.8 提取子字符串"></a>2.8 提取子字符串</h3><ul>
<li>以下实例从字符串第 <code>2</code> 个字符开始截取 <code>4</code> 个字符：</li>
</ul>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">author=<span class="string">'poetries'</span></span><br><span class="line"><span class="built_in">echo</span> <span class="string">"提取字符串：<span class="variable">$&#123;author:1:4&#125;</span>"</span> <span class="comment"># oetr</span></span><br></pre></td></tr></table></figure>
<h3 id="2-9-Shell-数组"><a href="#2-9-Shell-数组" class="headerlink" title="2.9 Shell 数组"></a>2.9 Shell 数组</h3><ul>
<li><code>bash</code>支持一维数组（不支持多维数组），并且没有限定数组的大小</li>
<li>类似与<code>C</code>语言，数组元素的下标由<code>0</code>开始编号。获取数组中的元素要利用下标，下标可以是整数或算术表达式，其值应大于或等于0</li>
</ul>
<h3 id="2-10-定义数组"><a href="#2-10-定义数组" class="headerlink" title="2.10 定义数组"></a>2.10 定义数组</h3><ul>
<li>在<code>Shell</code>中，用括号来表示数组，数组元素用”空格”符号分割开。定义数组的一般形式为：</li>
</ul>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">数组名=(值1 值2 ... 值n)</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">array_name=(value0 value1 value2 value3)</span><br></pre></td></tr></table></figure>
<p>或者</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">array_name=(</span><br><span class="line">value0</span><br><span class="line">value1</span><br><span class="line">value2</span><br><span class="line">value3</span><br><span class="line">)</span><br></pre></td></tr></table></figure>
<p>还可以单独定义数组的各个分量</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">array_name[0]=value0</span><br><span class="line">array_name[1]=value1</span><br><span class="line">array_name[n]=valuen</span><br></pre></td></tr></table></figure>
<h3 id="2-11-读取数组"><a href="#2-11-读取数组" class="headerlink" title="2.11 读取数组"></a>2.11 读取数组</h3><ul>
<li>读取数组元素值的一般格式是</li>
</ul>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">$&#123;数组名[下标]&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">valuen=$&#123;array_name[n]&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li>使用<code>@</code>符号可以获取数组中的所有元素，例如</li>
</ul>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">echo $&#123;array_name[@]&#125;</span><br></pre></td></tr></table></figure>
<h3 id="2-12-获取数组的长度"><a href="#2-12-获取数组的长度" class="headerlink" title="2.12 获取数组的长度"></a>2.12 获取数组的长度</h3><ul>
<li>获取数组长度的方法与获取字符串长度的方法相同，例如</li>
</ul>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line"># 取得数组元素的个数</span><br><span class="line">length=$&#123;#array_name[@]&#125;</span><br><span class="line"># 或者</span><br><span class="line">length=$&#123;#array_name[*]&#125;</span><br><span class="line"># 取得数组单个元素的长度</span><br><span class="line">lengthn=$&#123;#array_name[n]&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">like=(</span><br><span class="line">  <span class="string">'running'</span></span><br><span class="line">  <span class="string">'reading'</span></span><br><span class="line">  <span class="string">'play'</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="built_in">echo</span> <span class="string">"读取数组元素：<span class="variable">$&#123;like[@]&#125;</span>"</span> <span class="comment"># @读取数组所有长度</span></span><br></pre></td></tr></table></figure>
<h3 id="2-13-Shell-注释"><a href="#2-13-Shell-注释" class="headerlink" title="2.13 Shell 注释"></a>2.13 Shell 注释</h3><ul>
<li>以<code>&quot;#&quot;</code>开头的行就是注释，会被解释器忽略</li>
<li><code>sh</code>里没有多行注释，只能每一行加一个#号。只能像这样</li>
</ul>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="comment">#--------------------------------------------</span></span><br><span class="line"><span class="comment"># 这是一个注释</span></span><br><span class="line"><span class="comment"># author：poetry</span></span><br><span class="line"><span class="comment"># site：www.poetries.top！</span></span><br><span class="line"><span class="comment">#--------------------------------------------</span></span><br><span class="line"><span class="comment">##### 用户配置区 开始 #####</span></span><br><span class="line"><span class="comment">#</span></span><br><span class="line"><span class="comment">#</span></span><br><span class="line"><span class="comment"># 这里可以添加脚本描述信息</span></span><br><span class="line"><span class="comment"># </span></span><br><span class="line"><span class="comment">#</span></span><br><span class="line"><span class="comment">##### 用户配置区 结束  #####</span></span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="comment"># 学习记录</span></span><br><span class="line"></span><br><span class="line"><span class="meta">#!/bin/sh</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">echo</span> <span class="string">'====学习变量===='</span></span><br><span class="line">author=<span class="string">'poetries'</span></span><br><span class="line">like=(</span><br><span class="line">  <span class="string">'running'</span></span><br><span class="line">  <span class="string">'reading'</span></span><br><span class="line">  <span class="string">'playing'</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="built_in">echo</span> <span class="string">"读取数组元素：<span class="variable">$&#123;like[@]&#125;</span>"</span> <span class="comment"># @读取数组所有长度</span></span><br><span class="line"><span class="built_in">echo</span> <span class="string">"提取字符串：<span class="variable">$&#123;author:1:4&#125;</span>"</span></span><br><span class="line"><span class="built_in">echo</span> <span class="string">"字符串length:<span class="variable">$&#123;#author&#125;</span>"</span></span><br><span class="line"><span class="built_in">echo</span> <span class="string">"hello,I'm <span class="variable">$&#123;author&#125;</span>"</span></span><br></pre></td></tr></table></figure>
<h2 id="三、shell传递参数"><a href="#三、shell传递参数" class="headerlink" title="三、shell传递参数"></a>三、shell传递参数</h2><ul>
<li>我们可以在执行 <code>Shell</code> 脚本时，向脚本传递参数，脚本内获取参数的格式为：<code>$n</code>。<code>n</code> 代表一个数字，<code>1</code> 为执行脚本的第一个参数，<code>2</code> 为执行脚本的第二个参数，以此类推</li>
<li>以下实例我们向脚本传递三个参数，并分别输出，其中 <code>$0</code> 为执行的文件名</li>
</ul>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="comment"># sh test.sh 1 2 3 4</span></span><br><span class="line"></span><br><span class="line"><span class="meta">#!/bin/bash</span></span><br><span class="line"><span class="comment"># author:poetries</span></span><br><span class="line"><span class="comment"># url:blog.poetries.top</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">echo</span> <span class="string">"Shell 传递参数实例！"</span>;</span><br><span class="line"><span class="built_in">echo</span> <span class="string">"执行的文件名：<span class="variable">$0</span>"</span>;</span><br><span class="line"><span class="built_in">echo</span> <span class="string">"第一个参数为：<span class="variable">$1</span>"</span>;</span><br><span class="line"><span class="built_in">echo</span> <span class="string">"第二个参数为：<span class="variable">$2</span>"</span>;</span><br><span class="line"><span class="built_in">echo</span> <span class="string">"第三个参数为：<span class="variable">$3</span>"</span>;</span><br></pre></td></tr></table></figure>
<ul>
<li>为脚本设置可执行权限，并执行脚本，输出结果如下所示</li>
</ul>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">$ chmod +x test.sh </span><br><span class="line">$ ./test.sh 1 2 3</span><br><span class="line">Shell 传递参数实例！</span><br><span class="line">执行的文件名：./test.sh</span><br><span class="line">第一个参数为：1</span><br><span class="line">第二个参数为：2</span><br><span class="line">第三个参数为：3</span><br></pre></td></tr></table></figure>
<h2 id="四、数组"><a href="#四、数组" class="headerlink" title="四、数组"></a>四、数组</h2><ul>
<li>数组中可以存放多个值。<code>Bash Shell</code> 只支持一维数组（不支持多维数组），初始化时不需要定义数组大小</li>
<li>与大部分编程语言类似，数组元素的下标由<code>0</code>开始</li>
<li><code>Shell</code> 数组用括号来表示，元素用”空格”符号分割开，语法格式如下</li>
</ul>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="meta">#!/bin/bash</span></span><br><span class="line"><span class="comment"># author:poetry</span></span><br><span class="line"><span class="comment"># url:blog.poetries.top</span></span><br><span class="line"></span><br><span class="line">my_array=(A B <span class="string">"C"</span> D)</span><br></pre></td></tr></table></figure>
<ul>
<li>我们也可以使用下标来定义数组:</li>
</ul>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">array_name[0]=value0</span><br><span class="line">array_name[1]=value1</span><br><span class="line">array_name[2]=value2</span><br></pre></td></tr></table></figure>
<h3 id="4-1-读取数组"><a href="#4-1-读取数组" class="headerlink" title="4.1 读取数组"></a>4.1 读取数组</h3><figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="variable">$&#123;array_name[index]&#125;</span></span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="meta">#!/bin/bash</span></span><br><span class="line"><span class="comment"># author:poetry</span></span><br><span class="line"><span class="comment"># url:www.poetries.top</span></span><br><span class="line"></span><br><span class="line">my_array=(A B <span class="string">"C"</span> D)</span><br><span class="line"></span><br><span class="line"><span class="built_in">echo</span> <span class="string">"第一个元素为: <span class="variable">$&#123;my_array[0]&#125;</span>"</span></span><br><span class="line"><span class="built_in">echo</span> <span class="string">"第二个元素为: <span class="variable">$&#123;my_array[1]&#125;</span>"</span></span><br><span class="line"><span class="built_in">echo</span> <span class="string">"第三个元素为: <span class="variable">$&#123;my_array[2]&#125;</span>"</span></span><br><span class="line"><span class="built_in">echo</span> <span class="string">"第四个元素为: <span class="variable">$&#123;my_array[3]&#125;</span>"</span></span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">$ chmod +x test.sh </span><br><span class="line">$ ./test.sh</span><br><span class="line">第一个元素为: A</span><br><span class="line">第二个元素为: B</span><br><span class="line">第三个元素为: C</span><br><span class="line">第四个元素为: D</span><br></pre></td></tr></table></figure>
<h3 id="4-2-获取数组中的所有元素"><a href="#4-2-获取数组中的所有元素" class="headerlink" title="4.2 获取数组中的所有元素"></a>4.2 获取数组中的所有元素</h3><ul>
<li>使用<code>@</code> 或 <code>*</code> 可以获取数组中的所有元素，例如：</li>
</ul>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="meta">#!/bin/bash</span></span><br><span class="line"><span class="comment"># author:poetries</span></span><br><span class="line"><span class="comment"># url:www.poetries.top</span></span><br><span class="line"></span><br><span class="line">my_array[0]=A</span><br><span class="line">my_array[1]=B</span><br><span class="line">my_array[2]=C</span><br><span class="line">my_array[3]=D</span><br><span class="line"></span><br><span class="line"><span class="built_in">echo</span> <span class="string">"数组的元素为: <span class="variable">$&#123;my_array[*]&#125;</span>"</span></span><br><span class="line"><span class="built_in">echo</span> <span class="string">"数组的元素为: <span class="variable">$&#123;my_array[@]&#125;</span>"</span></span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">$ chmod +x test.sh </span><br><span class="line">$ ./test.sh</span><br><span class="line">数组的元素为: A B C D</span><br><span class="line">数组的元素为: A B C D</span><br></pre></td></tr></table></figure>
<h3 id="4-3-获取数组的长度"><a href="#4-3-获取数组的长度" class="headerlink" title="4.3 获取数组的长度"></a>4.3 获取数组的长度</h3><ul>
<li>获取数组长度的方法与获取字符串长度的方法相同，例如</li>
</ul>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="meta">#!/bin/bash</span></span><br><span class="line"><span class="comment"># author:poetries</span></span><br><span class="line"><span class="comment"># url:www.poetries.top</span></span><br><span class="line"></span><br><span class="line">my_array[0]=A</span><br><span class="line">my_array[1]=B</span><br><span class="line">my_array[2]=C</span><br><span class="line">my_array[3]=D</span><br><span class="line"></span><br><span class="line"><span class="built_in">echo</span> <span class="string">"数组元素个数为: <span class="variable">$&#123;#my_array[*]&#125;</span>"</span></span><br><span class="line"><span class="built_in">echo</span> <span class="string">"数组元素个数为: <span class="variable">$&#123;#my_array[@]&#125;</span>"</span></span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">$ chmod +x test.sh </span><br><span class="line">$ ./test.sh</span><br><span class="line">数组元素个数为: 4</span><br><span class="line">数组元素个数为: 4</span><br></pre></td></tr></table></figure>
<h2 id="五、基本运算符"><a href="#五、基本运算符" class="headerlink" title="五、基本运算符"></a>五、基本运算符</h2><ul>
<li>原生<code>bash</code>不支持简单的数学运算，但是可以通过其他命令来实现，例如 <code>awk</code> 和 <code>expr</code>，<code>expr</code> 最常用</li>
<li><code>expr</code> 是一款表达式计算工具，使用它能完成表达式的求值操作</li>
<li>例如，两个数相加(注意使用的是反引号 ` 而不是单引号 ‘)：</li>
</ul>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="meta">#!/bin/bash</span></span><br><span class="line"></span><br><span class="line">val=`expr 2 + 2` <span class="comment"># 注意 表达式和运算符之间要有空格</span></span><br><span class="line"><span class="built_in">echo</span> <span class="string">"两数之和为 : <span class="variable">$val</span>"</span></span><br></pre></td></tr></table></figure>
<ul>
<li>表达式和运算符之间要有空格，例如 <code>2+2</code> 是不对的，必须写成 <code>2 + 2</code>，这与我们熟悉的大多数编程语言不一样。</li>
<li>完整的表达式要被 <code></code> 包含，注意这个字符不是常用的单引号</li>
</ul>
<h3 id="5-1-算术运算符"><a href="#5-1-算术运算符" class="headerlink" title="5.1 算术运算符"></a>5.1 算术运算符</h3><ul>
<li>下表列出了常用的算术运算符，假定变量 <code>a</code> 为 <code>10</code>，变量 <code>b</code> 为 <code>20</code>：</li>
</ul>
<table>
<thead>
<tr>
<th>运算符</th>
<th>说明</th>
<th>举例</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>+</code></td>
<td>加法</td>
<td><code>expr $a + $b</code> 结果为 <code>30</code>。</td>
</tr>
<tr>
<td><code>-</code></td>
<td>减法</td>
<td><code>expr $a - $b</code> 结果为 <code>-10</code>。</td>
</tr>
<tr>
<td><code>*</code></td>
<td>乘法</td>
<td><code>expr $a \* $b</code> 结果为  <code>200</code>。</td>
</tr>
<tr>
<td><code>/</code></td>
<td>除法</td>
<td><code>expr $b / $a</code> 结果为 <code>2</code>。</td>
</tr>
<tr>
<td><code>%</code></td>
<td>取余</td>
<td><code>expr $b % $a</code> 结果为 <code>0</code>。</td>
</tr>
<tr>
<td><code>=</code></td>
<td>赋值</td>
<td><code>a=$b</code> 将把变量 b 的值赋给 a。</td>
</tr>
<tr>
<td><code>==</code></td>
<td>相等。用于比较两个数字，相同则返回 <code>true</code>。</td>
<td><code>[ $a == $b ]</code> 返回 <code>false</code>。</td>
</tr>
<tr>
<td><code>!=</code></td>
<td>不相等。用于比较两个数字，不相同则返回 <code>true</code>。</td>
<td><code>[ $a != $b ]</code> 返回 <code>true</code>。</td>
</tr>
</tbody>
</table>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="built_in">echo</span> <span class="string">'shell运算符学习===='</span></span><br><span class="line">value=`expr 2 + 3`</span><br><span class="line"><span class="built_in">echo</span> <span class="string">"两数之和:<span class="variable">$&#123;value&#125;</span>"</span></span><br><span class="line">a=10</span><br><span class="line">b=20</span><br><span class="line">add=`expr <span class="variable">$a</span> + <span class="variable">$b</span>`</span><br><span class="line">reduce=`expr <span class="variable">$a</span> - <span class="variable">$b</span>`</span><br><span class="line">cheng=`expr <span class="variable">$a</span> \* <span class="variable">$b</span>`</span><br><span class="line">chu=`expr <span class="variable">$a</span> / <span class="variable">$b</span>`</span><br><span class="line">quyu=`expr <span class="variable">$a</span> % <span class="variable">$b</span>`</span><br><span class="line"></span><br><span class="line"><span class="built_in">echo</span> <span class="string">"+：<span class="variable">$&#123;add&#125;</span>"</span></span><br><span class="line"><span class="built_in">echo</span> <span class="string">"-：<span class="variable">$&#123;reduce&#125;</span>"</span></span><br><span class="line"><span class="built_in">echo</span> <span class="string">"*：<span class="variable">$&#123;cheng&#125;</span>"</span></span><br><span class="line"><span class="built_in">echo</span> <span class="string">"/：<span class="variable">$&#123;chu&#125;</span>"</span></span><br><span class="line"><span class="built_in">echo</span> <span class="string">"%：<span class="variable">$&#123;quyu&#125;</span>"</span></span><br></pre></td></tr></table></figure>
<ul>
<li>注意：条件表达式要放在方括号之间，并且要有空格，例如: <code>[$a==$b]</code> 是错误的，必须写成 <code>[ $a == $b ]</code></li>
</ul>
<h3 id="5-2-关系运算符"><a href="#5-2-关系运算符" class="headerlink" title="5.2 关系运算符"></a>5.2 关系运算符</h3><ul>
<li>关系运算符只支持数字，不支持字符串，除非字符串的值是数字</li>
<li>下表列出了常用的关系运算符，假定变量 <code>a</code> 为 <code>10</code>，变量 <code>b</code> 为 <code>20</code>：</li>
</ul>
<table>
<thead>
<tr>
<th>运算符</th>
<th>说明</th>
<th>举例</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>-eq</code></td>
<td>检测两个数是否相等，相等返回 <code>true</code></td>
<td><code>[ $a -eq $b ]</code> 返回 <code>false</code></td>
</tr>
<tr>
<td><code>-ne</code></td>
<td>检测两个数是否相等，不相等返回 <code>true</code></td>
<td><code>[ $a -ne $b ]</code> 返回 <code>true</code></td>
<td>。</td>
</tr>
<tr>
<td><code>-gt</code></td>
<td>检测左边的数是否大于右边的，如果是，则返回 <code>true</code></td>
<td><code>[ $a -gt $b ]</code> 返回 <code>false</code></td>
</tr>
<tr>
<td><code>-lt</code></td>
<td>检测左边的数是否小于右边的，如果是，则返回 <code>true</code></td>
<td><code>[ $a -lt $b ]</code> 返回 <code>true</code></td>
</tr>
<tr>
<td><code>-ge</code></td>
<td>检测左边的数是否大于等于右边的，如果是，则返回 <code>true</code></td>
<td><code>[ $a -ge $b ]</code>返回 <code>false</code></td>
</tr>
<tr>
<td><code>-le</code></td>
<td>检测左边的数是否小于等于右边的，如果是，则返回 <code>true</code></td>
<td><code>[ $a -le $b ]</code>返回 <code>true</code></td>
</tr>
</tbody>
</table>
<h3 id="5-3-布尔运算符"><a href="#5-3-布尔运算符" class="headerlink" title="5.3 布尔运算符"></a>5.3 布尔运算符</h3><ul>
<li>下表列出了常用的布尔运算符，假定变量 <code>a</code> 为 <code>10</code>，变量 <code>b</code> 为 <code>20</code>：</li>
</ul>
<table>
<thead>
<tr>
<th>运算符</th>
<th>说明</th>
<th>举例</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>!</code></td>
<td>非运算，表达式为 <code>true</code> 则返回 <code>false</code>，否则返回 <code>true</code>。</td>
<td><code>[ ! false ]</code> 返回 <code>true</code></td>
</tr>
<tr>
<td><code>-o</code></td>
<td>或运算，有一个表达式为 <code>true</code>则返回 <code>true</code>。</td>
<td><code>[ $a -lt 20 -o $b -gt 100 ]</code> 返回 <code>true</code></td>
</tr>
<tr>
<td><code>-a</code></td>
<td>与运算，两个表达式都为 <code>true</code> 才返回 <code>true</code>。</td>
<td><code>[ $a -lt 20 -a $b -gt 100 ]</code>返回 <code>false</code></td>
</tr>
</tbody>
</table>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="meta">#!/bin/bash</span></span><br><span class="line"><span class="comment"># author:author</span></span><br><span class="line"><span class="comment"># url:blog.poetries.top</span></span><br><span class="line"></span><br><span class="line">a=10</span><br><span class="line">b=20</span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> [ <span class="variable">$a</span> != <span class="variable">$b</span> ]</span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"<span class="variable">$a</span> != <span class="variable">$b</span> : a 不等于 b"</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"<span class="variable">$a</span> != <span class="variable">$b</span>: a 等于 b"</span></span><br><span class="line"><span class="keyword">fi</span></span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="keyword">if</span> [ <span class="variable">$a</span> -lt 100 -a <span class="variable">$b</span> -gt 15 ]</span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"<span class="variable">$a</span> 小于 100 且 <span class="variable">$b</span> 大于 15 : 返回 true"</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"<span class="variable">$a</span> 小于 100 且 <span class="variable">$b</span> 大于 15 : 返回 false"</span></span><br><span class="line"><span class="keyword">fi</span></span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="keyword">if</span> [ <span class="variable">$a</span> -lt 100 -o <span class="variable">$b</span> -gt 100 ]</span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"<span class="variable">$a</span> 小于 100 或 <span class="variable">$b</span> 大于 100 : 返回 true"</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"<span class="variable">$a</span> 小于 100 或 <span class="variable">$b</span> 大于 100 : 返回 false"</span></span><br><span class="line"><span class="keyword">fi</span></span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="keyword">if</span> [ <span class="variable">$a</span> -lt 5 -o <span class="variable">$b</span> -gt 100 ]</span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"<span class="variable">$a</span> 小于 5 或 <span class="variable">$b</span> 大于 100 : 返回 true"</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"<span class="variable">$a</span> 小于 5 或 <span class="variable">$b</span> 大于 100 : 返回 false"</span></span><br><span class="line"><span class="keyword">fi</span></span><br></pre></td></tr></table></figure>
<h3 id="5-4-逻辑运算符"><a href="#5-4-逻辑运算符" class="headerlink" title="5.4 逻辑运算符"></a>5.4 逻辑运算符</h3><ul>
<li>以下介绍 Shell 的逻辑运算符，假定变量 <code>a</code> 为 <code>10</code>，变量 <code>b</code>为 <code>20</code></li>
</ul>
<table>
<thead>
<tr>
<th>运算符</th>
<th>说明</th>
<th>举例</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>&amp;&amp;</code></td>
<td>逻辑的 <code>AND</code></td>
<td><code>[[ $a -lt 100 &amp;&amp; $b -gt 100 ]]</code>返回 <code>false</code></td>
</tr>
<tr>
<td>`</td>
<td></td>
<td>`</td>
<td>逻辑的 <code>OR</code></td>
<td>`[[ $a -lt 100</td>
<td></td>
<td>$b -gt 100 ]]<code>返回</code>true`</td>
</tr>
</tbody>
</table>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="meta">#!/bin/bash</span></span><br><span class="line"></span><br><span class="line">a=10</span><br><span class="line">b=20</span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> [[ <span class="variable">$a</span> -lt 100 &amp;&amp; <span class="variable">$b</span> -gt 100 ]]</span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"返回 true"</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"返回 false"</span></span><br><span class="line"><span class="keyword">fi</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> [[ <span class="variable">$a</span> -lt 100 || <span class="variable">$b</span> -gt 100 ]]</span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"返回 true"</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"返回 false"</span></span><br><span class="line"><span class="keyword">fi</span></span><br></pre></td></tr></table></figure>
<h3 id="5-5-字符串运算符"><a href="#5-5-字符串运算符" class="headerlink" title="5.5 字符串运算符"></a>5.5 字符串运算符</h3><ul>
<li>下表列出了常用的字符串运算符，假定变量 <code>a</code> 为 <code>&quot;abc&quot;</code>，变量 <code>b</code> 为 <code>&quot;efg&quot;</code></li>
</ul>
<table>
<thead>
<tr>
<th>运算符</th>
<th>说明</th>
<th>举例</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>=</code></td>
<td>检测两个字符串是否相等，相等返回 <code>true</code></td>
<td><code>[ $a = $b ]</code> 返回 <code>false</code>。</td>
</tr>
<tr>
<td><code>!=</code></td>
<td>检测两个字符串是否相等，不相等返回 <code>true</code>。</td>
<td><code>[ $a != $b ]</code>返回 <code>true</code>。</td>
</tr>
<tr>
<td><code>-z</code></td>
<td>检测字符串长度是否为<code>0</code>，为<code>0</code>返回 <code>true</code>。</td>
<td><code>[ -z $a ]</code>返回 <code>false</code></td>
<td>。</td>
</tr>
<tr>
<td><code>-n</code></td>
<td>检测字符串长度是否为<code>0</code>，不为<code>0</code>返回 <code>true</code>。</td>
<td><code>[ -n $a ]</code> 返回 <code>true</code>。</td>
</tr>
<tr>
<td><code>str</code></td>
<td>检测字符串是否为空，不为空返回 <code>true</code>。</td>
<td><code>[ $a ]</code> 返回 <code>true</code>。</td>
</tr>
</tbody>
</table>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">a=<span class="string">"abc"</span></span><br><span class="line">b=<span class="string">"efg"</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> [ <span class="variable">$a</span> = <span class="variable">$b</span> ]</span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"<span class="variable">$a</span> = <span class="variable">$b</span> : a 等于 b"</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"<span class="variable">$a</span> = <span class="variable">$b</span>: a 不等于 b"</span></span><br><span class="line"><span class="keyword">fi</span></span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="keyword">if</span> [ <span class="variable">$a</span> != <span class="variable">$b</span> ]</span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"<span class="variable">$a</span> != <span class="variable">$b</span> : a 不等于 b"</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"<span class="variable">$a</span> != <span class="variable">$b</span>: a 等于 b"</span></span><br><span class="line"><span class="keyword">fi</span></span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="keyword">if</span> [ -z <span class="variable">$a</span> ]</span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"-z <span class="variable">$a</span> : 字符串长度为 0"</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"-z <span class="variable">$a</span> : 字符串长度不为 0"</span></span><br><span class="line"><span class="keyword">fi</span></span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="keyword">if</span> [ -n <span class="variable">$a</span> ]</span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"-n <span class="variable">$a</span> : 字符串长度不为 0"</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"-n <span class="variable">$a</span> : 字符串长度为 0"</span></span><br><span class="line"><span class="keyword">fi</span></span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="keyword">if</span> [ <span class="variable">$a</span> ]</span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"<span class="variable">$a</span> : 字符串不为空"</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"<span class="variable">$a</span> : 字符串为空"</span></span><br><span class="line"><span class="keyword">fi</span></span><br></pre></td></tr></table></figure>
<h3 id="5-6-文件测试运算符"><a href="#5-6-文件测试运算符" class="headerlink" title="5.6 文件测试运算符"></a>5.6 文件测试运算符</h3><ul>
<li>文件测试运算符用于检测 <code>Unix</code> 文件的各种属性</li>
</ul>
<table>
<thead>
<tr>
<th>操作符</th>
<th>说明</th>
<th>举例</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>-b file</code></td>
<td>检测文件是否是块设备文件，如果是，则返回 <code>true</code>。</td>
<td><code>[ -b $file ]</code>返回 <code>false</code>。</td>
</tr>
<tr>
<td><code>-c file</code></td>
<td>检测文件是否是字符设备文件，如果是，则返回 <code>true</code>。</td>
<td><code>[ -c $file ]</code>返回 <code>false</code>。</td>
</tr>
<tr>
<td><code>-d file</code></td>
<td>检测文件是否是目录，如果是，则返回 <code>true</code>。</td>
<td><code>[ -d $file ]</code> 返回 <code>false</code>。</td>
</tr>
<tr>
<td><code>-f file</code></td>
<td>检测文件是否是普通文件（既不是目录，也不是设备文件），如果是，则返回 <code>true</code>。</td>
<td><code>[ -f $file ]</code>返回 <code>true</code>。</td>
</tr>
<tr>
<td><code>-g file</code></td>
<td>检测文件是否设置了 <code>SGID</code>位，如果是，则返回 <code>true</code>。</td>
<td><code>[ -g $file ]</code> 返回 <code>false</code>。</td>
</tr>
<tr>
<td><code>-k file</code></td>
<td>检测文件是否设置了粘着位(<code>Sticky Bit</code>)，如果是，则返回 <code>true</code>。</td>
<td><code>[ -k $file ]</code> 返回 <code>false</code>。</td>
</tr>
<tr>
<td><code>-p file</code></td>
<td>检测文件是否是有名管道，如果是，则返回 <code>true</code>。</td>
<td><code>[ -p $file ]</code> 返回 <code>false</code>。</td>
</tr>
<tr>
<td><code>-u file</code></td>
<td>检测文件是否设置了 <code>SUID</code> 位，如果是，则返回 <code>true</code>。</td>
<td><code>[ -u $file ]</code> 返回 <code>false</code>。</td>
</tr>
<tr>
<td><code>-r file</code></td>
<td>检测文件是否可读，如果是，则返回 <code>true</code>。</td>
<td><code>[ -r $file ]</code> 返回 <code>true</code>。</td>
</tr>
<tr>
<td><code>-w file</code></td>
<td>检测文件是否可写，如果是，则返回 <code>true</code>。</td>
<td><code>[ -w $file ]</code> 返回 <code>true</code>。</td>
</tr>
<tr>
<td><code>-x file</code></td>
<td>检测文件是否可执行，如果是，则返回 <code>true</code>。</td>
<td><code>[ -x $file ]</code> 返回 <code>true</code>。</td>
</tr>
<tr>
<td><code>-s file</code></td>
<td>检测文件是否为空（文件大小是否大于<code>0</code>），不为空返回 <code>true</code>。</td>
<td><code>[ -s $file ]</code> 返回 <code>true</code>。</td>
</tr>
<tr>
<td><code>-e file</code></td>
<td>检测文件（包括目录）是否存在，如果是，则返回 <code>true</code>。</td>
<td><code>[ -e $file ]</code> 返回 <code>true</code>。</td>
</tr>
</tbody>
</table>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="meta">#!/bin/bash</span></span><br><span class="line"></span><br><span class="line">file=<span class="string">"/homee/shell/test1.sh"</span></span><br><span class="line"><span class="keyword">if</span> [ -r <span class="variable">$file</span> ]</span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"文件可读"</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"文件不可读"</span></span><br><span class="line"><span class="keyword">fi</span></span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="keyword">if</span> [ -w <span class="variable">$file</span> ]</span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"文件可写"</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"文件不可写"</span></span><br><span class="line"><span class="keyword">fi</span></span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="keyword">if</span> [ -x <span class="variable">$file</span> ]</span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"文件可执行"</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"文件不可执行"</span></span><br><span class="line"><span class="keyword">fi</span></span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="keyword">if</span> [ -f <span class="variable">$file</span> ]</span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"文件为普通文件"</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"文件为特殊文件"</span></span><br><span class="line"><span class="keyword">fi</span></span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="keyword">if</span> [ -d <span class="variable">$file</span> ]</span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"文件是个目录"</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"文件不是个目录"</span></span><br><span class="line"><span class="keyword">fi</span></span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="keyword">if</span> [ -s <span class="variable">$file</span> ]</span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"文件不为空"</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"文件为空"</span></span><br><span class="line"><span class="keyword">fi</span></span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="keyword">if</span> [ -e <span class="variable">$file</span> ]</span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"文件存在"</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"文件不存在"</span></span><br><span class="line"><span class="keyword">fi</span></span><br></pre></td></tr></table></figure>
<h2 id="六、echo用法"><a href="#六、echo用法" class="headerlink" title="六、echo用法"></a>六、echo用法</h2><ul>
<li><code>Shell</code> 的 <code>echo</code> 指令与 <code>PHP</code> 的 <code>echo</code> 指令类似，都是用于字符串的输出。命令格式</li>
</ul>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="built_in">echo</span> string</span><br></pre></td></tr></table></figure>
<h3 id="6-1-显示普通字符串"><a href="#6-1-显示普通字符串" class="headerlink" title="6.1 显示普通字符串:"></a>6.1 显示普通字符串:</h3><figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="built_in">echo</span> <span class="string">"It is a test"</span></span><br></pre></td></tr></table></figure>
<ul>
<li>这里的双引号完全可以省略，以下命令与上面实例效果一致</li>
</ul>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="built_in">echo</span> It is a <span class="built_in">test</span></span><br></pre></td></tr></table></figure>
<h3 id="6-2-显示转义字符"><a href="#6-2-显示转义字符" class="headerlink" title="6.2 显示转义字符"></a>6.2 显示转义字符</h3><figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="built_in">echo</span> <span class="string">"\"It is a test\""</span></span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">&quot;It is a test&quot;</span><br></pre></td></tr></table></figure>
<h3 id="6-3-显示变量"><a href="#6-3-显示变量" class="headerlink" title="6.3 显示变量"></a>6.3 显示变量</h3><ul>
<li><code>read</code> 命令从标准输入中读取一行,并把输入行的每个字段的值指定给 shell 变量</li>
</ul>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="meta">#!/bin/sh</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">read</span> name </span><br><span class="line"><span class="built_in">echo</span> <span class="string">"<span class="variable">$name</span> It is a test"</span></span><br></pre></td></tr></table></figure>
<ul>
<li>以上代码保存为 <code>test.sh</code>，<code>name</code> 接收标准输入的变量，结果将是</li>
</ul>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">[root@www ~]<span class="comment"># sh test.sh</span></span><br><span class="line">poetry                     <span class="comment">#标准输入</span></span><br><span class="line">poetry It is a <span class="built_in">test</span>        <span class="comment">#输出</span></span><br></pre></td></tr></table></figure>
<h3 id="6-4-显示换行"><a href="#6-4-显示换行" class="headerlink" title="6.4 显示换行"></a>6.4 显示换行</h3><figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="built_in">echo</span> -e <span class="string">"OK! \n"</span> <span class="comment"># -e 开启转义</span></span><br><span class="line"><span class="built_in">echo</span> <span class="string">"It it a test"</span></span><br></pre></td></tr></table></figure>
<h3 id="6-5-显示不换行"><a href="#6-5-显示不换行" class="headerlink" title="6.5 显示不换行"></a>6.5 显示不换行</h3><figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="meta">#!/bin/sh</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">echo</span> -e <span class="string">"OK! \c"</span> <span class="comment"># -e 开启转义 \c 不换行</span></span><br><span class="line"><span class="built_in">echo</span> <span class="string">"It is a test"</span></span><br></pre></td></tr></table></figure>
<h3 id="6-6-显示结果定向至文件"><a href="#6-6-显示结果定向至文件" class="headerlink" title="6.6 显示结果定向至文件"></a>6.6 显示结果定向至文件</h3><figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="built_in">echo</span> <span class="string">"It is a test"</span> &gt; myfile</span><br></pre></td></tr></table></figure>
<h3 id="6-7-显示命令执行结果"><a href="#6-7-显示命令执行结果" class="headerlink" title="6.7 显示命令执行结果"></a>6.7 显示命令执行结果</h3><figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="built_in">echo</span> `date`</span><br></pre></td></tr></table></figure>
<ul>
<li>注意： 这里使用的是反引号 `, 而不是单引号 ‘</li>
<li>结果将显示当前日期</li>
</ul>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">Thu Feb 22 14:34:57 GMT 2018</span><br></pre></td></tr></table></figure>
<h2 id="七、printf用法"><a href="#七、printf用法" class="headerlink" title="七、printf用法"></a>七、printf用法</h2><ul>
<li><code>printf</code> 命令模仿 <code>C</code> 程序库（<code>library</code>）里的 <code>printf()</code> 程序</li>
<li><code>printf</code> 由 <code>POSIX</code> 标准所定义，因此使用 <code>printf</code> 的脚本比使用 <code>echo</code> 移植性好</li>
<li>默认 <code>printf</code> 不会像 <code>echo</code>自动添加换行符，我们可以手动添加 <code>\n</code></li>
</ul>
<p><strong>printf 命令的语法</strong></p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="built_in">printf</span>  format-string  [arguments...]</span><br></pre></td></tr></table></figure>
<ul>
<li><code>format-string</code>: 为格式控制字符串</li>
<li><code>arguments</code>: 为参数列表</li>
</ul>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">$ <span class="built_in">echo</span> <span class="string">"Hello, Shell"</span></span><br><span class="line">Hello, Shell</span><br><span class="line"></span><br><span class="line">$ <span class="built_in">printf</span> <span class="string">"Hello, Shell\n"</span></span><br><span class="line">Hello, Shell</span><br><span class="line">$</span><br></pre></td></tr></table></figure>
<ul>
<li>接下来,用一个脚本来体现<code>printf</code>的强大功能</li>
</ul>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="meta">#!/bin/bash</span></span><br><span class="line"> </span><br><span class="line"><span class="built_in">printf</span> <span class="string">"%-10s %-8s %-4s\n"</span> 姓名 性别 体重kg  </span><br><span class="line"><span class="built_in">printf</span> <span class="string">"%-10s %-8s %-4.2f\n"</span> 郭靖 男 66.1234 </span><br><span class="line"><span class="built_in">printf</span> <span class="string">"%-10s %-8s %-4.2f\n"</span> 杨过 男 48.6543 </span><br><span class="line"><span class="built_in">printf</span> <span class="string">"%-10s %-8s %-4.2f\n"</span> 郭芙 女 47.9876</span><br></pre></td></tr></table></figure>
<ul>
<li>执行脚本，输出结果如下所示</li>
</ul>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">姓名     性别   体重kg</span><br><span class="line">郭靖     男      66.12</span><br><span class="line">杨过     男      48.65</span><br><span class="line">郭芙     女      47.99</span><br></pre></td></tr></table></figure>
<ul>
<li><code>%s</code> <code>%c</code> <code>%d</code> <code>%f</code>都是格式替代符</li>
<li><code>%-10s</code> 指一个宽度为<code>10</code>个字符（<code>-</code>表示左对齐，没有则表示右对齐），任何字符都会被显示在<code>10</code>个字符宽的字符内，如果不足则自动以空格填充，超过也会将内容全部显示出来</li>
<li><code>%-4.2f</code> 指格式化为小数，其中<code>.2</code>指保留<code>2</code>位小数</li>
</ul>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="meta">#!/bin/bash</span></span><br><span class="line"> </span><br><span class="line"><span class="comment"># format-string为双引号</span></span><br><span class="line"><span class="built_in">printf</span> <span class="string">"%d %s\n"</span> 1 <span class="string">"abc"</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 单引号与双引号效果一样 </span></span><br><span class="line"><span class="built_in">printf</span> <span class="string">'%d %s\n'</span> 1 <span class="string">"abc"</span> </span><br><span class="line"></span><br><span class="line"><span class="comment"># 没有引号也可以输出</span></span><br><span class="line"><span class="built_in">printf</span> %s abcdef</span><br><span class="line"></span><br><span class="line"><span class="comment"># 格式只指定了一个参数，但多出的参数仍然会按照该格式输出，format-string 被重用</span></span><br><span class="line"><span class="built_in">printf</span> %s abc def</span><br><span class="line"></span><br><span class="line"><span class="built_in">printf</span> <span class="string">"%s\n"</span> abc def</span><br><span class="line"></span><br><span class="line"><span class="built_in">printf</span> <span class="string">"%s %s %s\n"</span> a b c d e f g h i j</span><br><span class="line"></span><br><span class="line"><span class="comment"># 如果没有 arguments，那么 %s 用NULL代替，%d 用 0 代替</span></span><br><span class="line"><span class="built_in">printf</span> <span class="string">"%s and %d \n"</span></span><br></pre></td></tr></table></figure>
<p><strong>printf的转义序列</strong></p>
<table>
<thead>
<tr>
<th>序列</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>\a</code></td>
<td>警告字符，通常为<code>ASCII</code>的<code>BEL</code>字符</td>
</tr>
<tr>
<td><code>\b</code></td>
<td>后退</td>
</tr>
<tr>
<td><code>\c</code></td>
<td>抑制（不显示）输出结果中任何结尾的换行字符（只在<code>%b</code>格式指示符控制下的参数字符串中有效），而且，任何留在参数里的字符、任何接下来的参数以及任何留在格式字符串中的字符，都被忽略</td>
</tr>
<tr>
<td><code>\f</code></td>
<td>换页（formfeed）</td>
</tr>
<tr>
<td><code>\n</code></td>
<td>换行</td>
</tr>
<tr>
<td><code>\r</code></td>
<td>回车（Carriage return）</td>
</tr>
<tr>
<td><code>\t</code></td>
<td>水平制表符</td>
</tr>
<tr>
<td><code>\v</code></td>
<td>垂直制表符</td>
</tr>
<tr>
<td><code>\\</code></td>
<td>一个字面上的反斜杠字符</td>
</tr>
<tr>
<td><code>\ddd</code></td>
<td>表示1到3位数八进制值的字符。仅在格式字符串中有效</td>
</tr>
<tr>
<td><code>\0ddd</code></td>
<td>表示1到3位的八进制值字符</td>
</tr>
</tbody>
</table>
<h2 id="八、test命令"><a href="#八、test命令" class="headerlink" title="八、test命令"></a>八、test命令</h2><ul>
<li><code>Shell</code>中的 <code>test</code> 命令用于检查某个条件是否成立，它可以进行数值、字符和文件三个方面的测试。</li>
</ul>
<h3 id="8-1-数值测试"><a href="#8-1-数值测试" class="headerlink" title="8.1 数值测试"></a>8.1 数值测试</h3><table>
<thead>
<tr>
<th>参数</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>-eq</code></td>
<td>等于则为真</td>
</tr>
<tr>
<td><code>-ne</code></td>
<td>不等于则为真</td>
</tr>
<tr>
<td><code>-gt</code></td>
<td>大于则为真</td>
</tr>
<tr>
<td><code>-ge</code></td>
<td>大于等于则为真</td>
</tr>
<tr>
<td><code>-lt</code></td>
<td>小于则为真</td>
</tr>
<tr>
<td><code>-le</code></td>
<td>小于等于则为真</td>
</tr>
</tbody>
</table>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">num1=100</span><br><span class="line">num2=100</span><br><span class="line"><span class="keyword">if</span> <span class="built_in">test</span> $[num1] -eq $[num2]</span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">    <span class="built_in">echo</span> <span class="string">'两个数相等！'</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">    <span class="built_in">echo</span> <span class="string">'两个数不相等！'</span></span><br><span class="line"><span class="keyword">fi</span></span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">两个数相等！</span><br></pre></td></tr></table></figure>
<ul>
<li>代码中的 <code>[]</code> 执行基本的算数运算</li>
</ul>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="meta">#!/bin/bash</span></span><br><span class="line"></span><br><span class="line">a=5</span><br><span class="line">b=6</span><br><span class="line"></span><br><span class="line">result=$[a+b] <span class="comment"># 注意等号两边不能有空格</span></span><br><span class="line"><span class="built_in">echo</span> <span class="string">"result 为： <span class="variable">$result</span>"</span></span><br></pre></td></tr></table></figure>
<h3 id="8-2-字符串测试"><a href="#8-2-字符串测试" class="headerlink" title="8.2 字符串测试"></a>8.2 字符串测试</h3><table>
<thead>
<tr>
<th>参数</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td>`=</td>
<td>`    等于则为真</td>
</tr>
<tr>
<td><code>!=</code></td>
<td>不相等则为真</td>
</tr>
<tr>
<td><code>-z</code></td>
<td>字符串</td>
<td>字符串的长度为零则为真</td>
</tr>
<tr>
<td><code>-n</code></td>
<td>字符串</td>
<td>字符串的长度不为零则为真</td>
</tr>
</tbody>
</table>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">num1=<span class="string">"poetries"</span></span><br><span class="line">num2=<span class="string">"poetries1"</span></span><br><span class="line"><span class="keyword">if</span> <span class="built_in">test</span> <span class="variable">$num1</span> = <span class="variable">$num2</span></span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">    <span class="built_in">echo</span> <span class="string">'两个字符串相等!'</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">    <span class="built_in">echo</span> <span class="string">'两个字符串不相等!'</span></span><br><span class="line"><span class="keyword">fi</span></span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">两个字符串不相等!</span><br></pre></td></tr></table></figure>
<h3 id="8-3-文件测试"><a href="#8-3-文件测试" class="headerlink" title="8.3 文件测试"></a>8.3 文件测试</h3><table>
<thead>
<tr>
<th>参数</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>-e</code> 文件名</td>
<td>如果文件存在则为真</td>
</tr>
<tr>
<td><code>-r</code> 文件名</td>
<td>如果文件存在且可读则为真</td>
</tr>
<tr>
<td><code>-w</code>文件名</td>
<td>如果文件存在且可写则为真</td>
</tr>
<tr>
<td><code>-x</code> 文件名</td>
<td>如果文件存在且可执行则为真</td>
</tr>
<tr>
<td><code>-s</code> 文件名</td>
<td>如果文件存在且至少有一个字符则为真</td>
</tr>
<tr>
<td><code>-d</code> 文件名</td>
<td>如果文件存在且为目录则为真</td>
</tr>
<tr>
<td><code>-f</code> 文件名</td>
<td>如果文件存在且为普通文件则为真</td>
</tr>
<tr>
<td><code>-c</code> 文件名</td>
<td>如果文件存在且为字符型特殊文件则为真</td>
</tr>
<tr>
<td><code>-b</code> 文件名</td>
<td>如果文件存在且为块特殊文件则为真</td>
</tr>
</tbody>
</table>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">file=/home/shell/test.sh</span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> <span class="built_in">test</span> -e <span class="variable">$file</span></span><br><span class="line"><span class="keyword">then</span></span><br><span class="line"> <span class="built_in">echo</span> <span class="string">'test.sh文件存在'</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line"> <span class="built_in">echo</span> <span class="string">'test.sh不存在'</span></span><br><span class="line"><span class="keyword">fi</span></span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">test.sh文件存在</span><br></pre></td></tr></table></figure>
<ul>
<li>另外，<code>Shell</code>还提供了与( <code>-a</code> )、或( <code>-o</code> )、非( <code>!</code> )三个逻辑操作符用于将测试条件连接起来，其优先级为：”<code>!</code>“最高，”<code>-a</code>“次之，”<code>-o</code>“最低。例如：</li>
</ul>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">file=/home/shell/test.sh</span><br><span class="line">file1=/home/poetry</span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> <span class="built_in">test</span> -d <span class="variable">$file1</span> -o -e <span class="variable">$file</span></span><br><span class="line"><span class="keyword">then</span></span><br><span class="line"> <span class="built_in">echo</span> <span class="string">'至少有一个文件存在'</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line"> <span class="built_in">echo</span> <span class="string">'两个文件都不存在'</span></span><br><span class="line"><span class="keyword">fi</span></span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">有一个文件存在!</span><br></pre></td></tr></table></figure>
<h2 id="九、流程控制if-while-case"><a href="#九、流程控制if-while-case" class="headerlink" title="九、流程控制if/while/case"></a>九、流程控制if/while/case</h2><h3 id="9-1-if"><a href="#9-1-if" class="headerlink" title="9.1 if"></a>9.1 if</h3><ul>
<li><code>if</code> 语句语法格式</li>
</ul>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="keyword">if</span> condition</span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">    command1 </span><br><span class="line">    command2</span><br><span class="line">    ...</span><br><span class="line">    commandN </span><br><span class="line"><span class="keyword">fi</span></span><br></pre></td></tr></table></figure>
<ul>
<li>写成一行（适用于终端命令提示符）</li>
</ul>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="keyword">if</span> [ $(ps -ef | grep -c <span class="string">"ssh"</span>) -gt 1 ]; <span class="keyword">then</span> <span class="built_in">echo</span> <span class="string">"true"</span>; <span class="keyword">fi</span></span><br></pre></td></tr></table></figure>
<h3 id="9-2-if-else"><a href="#9-2-if-else" class="headerlink" title="9.2 if else"></a>9.2 if else</h3><figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="keyword">if</span> condition</span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">    command1 </span><br><span class="line">    command2</span><br><span class="line">    ...</span><br><span class="line">    commandN</span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">    <span class="built_in">command</span></span><br><span class="line"><span class="keyword">fi</span></span><br></pre></td></tr></table></figure>
<h3 id="9-3-if-else-if-else"><a href="#9-3-if-else-if-else" class="headerlink" title="9.3 if else-if else"></a>9.3 if else-if else</h3><figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="keyword">if</span> condition1</span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">    command1</span><br><span class="line"><span class="keyword">elif</span> condition2 </span><br><span class="line"><span class="keyword">then</span> </span><br><span class="line">    command2</span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">    commandN</span><br><span class="line"><span class="keyword">fi</span></span><br></pre></td></tr></table></figure>
<ul>
<li>以下实例判断两个变量是否相等</li>
</ul>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">a=10</span><br><span class="line">b=20</span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> [ <span class="variable">$a</span> == <span class="variable">$b</span> ]</span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"a 等于 b"</span></span><br><span class="line"><span class="keyword">elif</span> [ <span class="variable">$a</span> -gt <span class="variable">$b</span> ]</span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"a 大于 b"</span></span><br><span class="line"><span class="keyword">elif</span> [ <span class="variable">$a</span> -lt <span class="variable">$b</span> ]</span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"a 小于 b"</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="string">"没有符合的条件"</span></span><br><span class="line"><span class="keyword">fi</span></span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">a 小于 b</span><br></pre></td></tr></table></figure>
<ul>
<li><code>if else</code>语句经常与<code>test</code>命令结合使用，如下所示</li>
</ul>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">num1=$[2*3]</span><br><span class="line">num2=$[1+5]</span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> <span class="built_in">test</span> $[num1] -eq $[num2]</span><br><span class="line"><span class="keyword">then</span></span><br><span class="line">    <span class="built_in">echo</span> <span class="string">'两个数字相等!'</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">    <span class="built_in">echo</span> <span class="string">'两个数字不相等!'</span></span><br><span class="line"><span class="keyword">fi</span></span><br></pre></td></tr></table></figure>
<h3 id="9-4-for-循环"><a href="#9-4-for-循环" class="headerlink" title="9.4 for 循环"></a>9.4 for 循环</h3><figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="keyword">for</span> var <span class="keyword">in</span> item1 item2 ... itemN</span><br><span class="line"><span class="keyword">do</span></span><br><span class="line">    command1</span><br><span class="line">    command2</span><br><span class="line">    ...</span><br><span class="line">    commandN</span><br><span class="line"><span class="keyword">done</span></span><br></pre></td></tr></table></figure>
<ul>
<li>写成一行</li>
</ul>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="keyword">for</span> var <span class="keyword">in</span> item1 item2 ... itemN; <span class="keyword">do</span> command1; command2… <span class="keyword">done</span>;</span><br></pre></td></tr></table></figure>
<ul>
<li>当变量值在列表里，<code>for</code>循环即执行一次所有命令，使用变量名获取列表中的当前取值。</li>
<li>命令可为任何有效的<code>shell</code>命令和语句</li>
<li><code>in</code>列表可以包含替换、字符串和文件名</li>
<li><code>in</code>列表是可选的，如果不用它，<code>for</code>循环使用命令行的位置参数</li>
</ul>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="keyword">for</span> loop <span class="keyword">in</span> 1 2 3 4 5</span><br><span class="line"><span class="keyword">do</span></span><br><span class="line">    <span class="built_in">echo</span> <span class="string">"The value is: <span class="variable">$loop</span>"</span></span><br><span class="line"><span class="keyword">done</span></span><br></pre></td></tr></table></figure>
<p>输出</p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">The value is: 1</span><br><span class="line">The value is: 2</span><br><span class="line">The value is: 3</span><br><span class="line">The value is: 4</span><br><span class="line">The value is: 5</span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="keyword">for</span> str <span class="keyword">in</span> <span class="string">'This is a string'</span></span><br><span class="line"><span class="keyword">do</span></span><br><span class="line">  <span class="built_in">echo</span> <span class="variable">$str</span></span><br><span class="line"><span class="keyword">done</span></span><br></pre></td></tr></table></figure>
<p>输出</p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">This is a string</span><br></pre></td></tr></table></figure>
<h3 id="9-5-while-语句"><a href="#9-5-while-语句" class="headerlink" title="9.5 while 语句"></a>9.5 while 语句</h3><ul>
<li><code>while</code>循环用于不断执行一系列命令，也用于从输入文件中读取数据；命令通常为测试条件。其格式为</li>
</ul>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="keyword">while</span> condition</span><br><span class="line"><span class="keyword">do</span></span><br><span class="line">    <span class="built_in">command</span></span><br><span class="line"><span class="keyword">done</span></span><br></pre></td></tr></table></figure>
<ul>
<li>以下是一个基本的<code>while</code>循环，测试条件是：如果<code>int</code>小于等于<code>5</code>，那么条件返回真。<code>int</code>从<code>0</code>开始，每次循环处理时，<code>int</code>加<code>1</code>。运行上述脚本，返回数字<code>1</code>到<code>5</code>，然后终止</li>
<li>使用中使用了 <code>Bash let</code> 命令，它用于执行一个或多个表达式，变量计算中不需要加上 <code>$</code> 来表示变量</li>
</ul>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="meta">#!/bin/sh</span></span><br><span class="line"></span><br><span class="line">int=1</span><br><span class="line"></span><br><span class="line"><span class="keyword">while</span>(( <span class="variable">$int</span>&lt;=5 ))</span><br><span class="line"><span class="keyword">do</span></span><br><span class="line">    <span class="built_in">echo</span> <span class="variable">$int</span></span><br><span class="line">    <span class="built_in">let</span> <span class="string">"int++"</span></span><br><span class="line"><span class="keyword">done</span></span><br></pre></td></tr></table></figure>
<h3 id="9-6-until-循环"><a href="#9-6-until-循环" class="headerlink" title="9.6 until 循环"></a>9.6 until 循环</h3><ul>
<li><code>until</code>循环执行一系列命令直至条件为真时停止</li>
<li><code>until</code>循环与<code>while</code>循环在处理方式上刚好相反</li>
<li>一般<code>while</code>循环优于<code>until</code>循环，但在某些时候—也只是极少数情况下，<code>until</code>循环更加有用</li>
</ul>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">until condition</span><br><span class="line"><span class="keyword">do</span></span><br><span class="line">    <span class="built_in">command</span></span><br><span class="line"><span class="keyword">done</span></span><br></pre></td></tr></table></figure>
<h3 id="9-7-case"><a href="#9-7-case" class="headerlink" title="9.7 case"></a>9.7 case</h3><ul>
<li><code>Shell case</code>语句为多选择语句。可以用<code>case</code>语句匹配一个值与一个模式，如果匹配成功，执行相匹配的命令。<code>case</code>语句格式如下：</li>
</ul>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="keyword">case</span> 值 <span class="keyword">in</span></span><br><span class="line">模式1)</span><br><span class="line">    command1</span><br><span class="line">    command2</span><br><span class="line">    ...</span><br><span class="line">    commandN</span><br><span class="line">    ;;</span><br><span class="line">模式2）</span><br><span class="line">    command1</span><br><span class="line">    command2</span><br><span class="line">    ...</span><br><span class="line">    commandN</span><br><span class="line">    ;;</span><br><span class="line"><span class="keyword">esac</span></span><br></pre></td></tr></table></figure>
<ul>
<li><code>case</code>工作方式如上所示。取值后面必须为单词<code>in</code>，每一模式必须以右括号结束。取值可以为变量或常数。匹配发现取值符合某一模式后，其间所有命令开始执行直至</li>
<li>取值将检测匹配的每一个模式。一旦模式匹配，则执行完匹配模式相应命令后不再继续其他模式。如果无一匹配模式，使用星号 <code>*</code> 捕获该值，再执行后面的命令</li>
<li>下面的脚本提示输入<code>1</code>到<code>4</code>，与每一种模式进行匹配</li>
</ul>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="built_in">echo</span> <span class="string">'输入 1 到 4 之间的数字:'</span></span><br><span class="line"><span class="built_in">echo</span> <span class="string">'你输入的数字为:'</span></span><br><span class="line"><span class="built_in">read</span> aNum</span><br><span class="line"><span class="keyword">case</span> <span class="variable">$aNum</span> <span class="keyword">in</span></span><br><span class="line">    1)  <span class="built_in">echo</span> <span class="string">'你选择了 1'</span></span><br><span class="line">    ;;</span><br><span class="line">    2)  <span class="built_in">echo</span> <span class="string">'你选择了 2'</span></span><br><span class="line">    ;;</span><br><span class="line">    3)  <span class="built_in">echo</span> <span class="string">'你选择了 3'</span></span><br><span class="line">    ;;</span><br><span class="line">    4)  <span class="built_in">echo</span> <span class="string">'你选择了 4'</span></span><br><span class="line">    ;;</span><br><span class="line">    *)  <span class="built_in">echo</span> <span class="string">'你没有输入 1 到 4 之间的数字'</span></span><br><span class="line">    ;;</span><br><span class="line"><span class="keyword">esac</span></span><br></pre></td></tr></table></figure>
<h3 id="9-8-跳出循环"><a href="#9-8-跳出循环" class="headerlink" title="9.8 跳出循环"></a>9.8 跳出循环</h3><ul>
<li>在循环过程中，有时候需要在未达到循环结束条件时强制跳出循环，Shell使用两个命令来实现该功能：<code>break</code>和<code>continue</code></li>
</ul>
<p><strong>break命令</strong></p>
<ul>
<li><code>break</code>命令允许跳出所有循环（终止执行后面的所有循环）</li>
<li>下面的例子中，脚本进入死循环直至用户输入数字大于5。要跳出这个循环，返回到<code>shell</code>提示符下，需要使用<code>break</code>命令</li>
</ul>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="meta">#!/bin/bash</span></span><br><span class="line"><span class="keyword">while</span> :</span><br><span class="line"><span class="keyword">do</span></span><br><span class="line">    <span class="built_in">echo</span> -n <span class="string">"输入 1 到 5 之间的数字:"</span></span><br><span class="line">    <span class="built_in">read</span> aNum</span><br><span class="line">    <span class="keyword">case</span> <span class="variable">$aNum</span> <span class="keyword">in</span></span><br><span class="line">        1|2|3|4|5) <span class="built_in">echo</span> <span class="string">"你输入的数字为 <span class="variable">$aNum</span>!"</span></span><br><span class="line">        ;;</span><br><span class="line">        *) <span class="built_in">echo</span> <span class="string">"你输入的数字不是 1 到 5 之间的! 游戏结束"</span></span><br><span class="line">            <span class="built_in">break</span></span><br><span class="line">        ;;</span><br><span class="line">    <span class="keyword">esac</span></span><br><span class="line"><span class="keyword">done</span></span><br></pre></td></tr></table></figure>
<h3 id="9-9-continue"><a href="#9-9-continue" class="headerlink" title="9.9 continue"></a>9.9 continue</h3><ul>
<li><code>continue</code>命令与<code>break</code>命令类似，只有一点差别，它不会跳出所有循环，仅仅跳出当前循环</li>
</ul>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="meta">#!/bin/bash</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">while</span> :</span><br><span class="line"><span class="keyword">do</span></span><br><span class="line">    <span class="built_in">echo</span> -n <span class="string">"输入 1 到 5 之间的数字: "</span></span><br><span class="line">    <span class="built_in">read</span> aNum</span><br><span class="line">    <span class="keyword">case</span> <span class="variable">$aNum</span> <span class="keyword">in</span></span><br><span class="line">        1|2|3|4|5) <span class="built_in">echo</span> <span class="string">"你输入的数字为 <span class="variable">$aNum</span>!"</span></span><br><span class="line">        ;;</span><br><span class="line">        *) <span class="built_in">echo</span> <span class="string">"你输入的数字不是 1 到 5 之间的!"</span></span><br><span class="line">            <span class="built_in">continue</span></span><br><span class="line">            <span class="built_in">echo</span> <span class="string">"游戏结束"</span></span><br><span class="line">        ;;</span><br><span class="line">    <span class="keyword">esac</span></span><br><span class="line"><span class="keyword">done</span></span><br></pre></td></tr></table></figure>
<h2 id="十、函数"><a href="#十、函数" class="headerlink" title="十、函数"></a>十、函数</h2><ul>
<li>linux shell 可以定义函数，然后在shell脚本中可以随便调用。</li>
<li>shell中函数的定义格式如下</li>
</ul>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">[ <span class="keyword">function</span> ] funname [()]</span><br><span class="line"></span><br><span class="line">&#123;</span><br><span class="line"></span><br><span class="line">    action;</span><br><span class="line"></span><br><span class="line">    [<span class="built_in">return</span> int;]</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li>可以带<code>function fun()</code> 定义，也可以直接<code>fun()</code> 定义,不带任何参数。</li>
<li>参数返回，可以显示加：<code>return</code> 返回，如果不加，将以最后一条命令运行结果，作为返回值。 <code>return</code>后跟数值<code>n(0-255)</code></li>
</ul>
<blockquote>
<p>下面的例子定义了一个函数并进行调用</p>
</blockquote>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="meta">#!/bin/bash</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="title">demoFun</span></span>()&#123;</span><br><span class="line">    <span class="built_in">echo</span> <span class="string">"这是我的第一个 shell 函数!"</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">echo</span> <span class="string">"-----函数开始执行-----"</span></span><br><span class="line">demoFun</span><br><span class="line"><span class="built_in">echo</span> <span class="string">"-----函数执行完毕-----"</span></span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">-----函数开始执行-----</span><br><span class="line">这是我的第一个 shell 函数!</span><br><span class="line">-----函数执行完毕-----</span><br></pre></td></tr></table></figure>
<ul>
<li>下面定义一个带有<code>return</code>语句的函数</li>
</ul>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="meta">#!/bin/bash</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="title">fun</span></span>()&#123;</span><br><span class="line">    <span class="built_in">echo</span> <span class="string">"这个函数会对输入的两个数字进行相加运算..."</span></span><br><span class="line">    <span class="built_in">echo</span> <span class="string">"输入第一个数字: "</span></span><br><span class="line">    <span class="built_in">read</span> aNum</span><br><span class="line">    <span class="built_in">echo</span> <span class="string">"输入第二个数字: "</span></span><br><span class="line">    <span class="built_in">read</span> anotherNum</span><br><span class="line">    <span class="built_in">echo</span> <span class="string">"两个数字分别为 <span class="variable">$aNum</span> 和 <span class="variable">$anotherNum</span> !"</span></span><br><span class="line">    <span class="built_in">return</span> $((<span class="variable">$aNum</span>+<span class="variable">$anotherNum</span>))</span><br><span class="line">&#125;</span><br><span class="line">sum=fun</span><br><span class="line"><span class="built_in">echo</span> <span class="string">"输入的两个数字之和为 <span class="variable">$&#123;sum&#125;</span>"</span></span><br></pre></td></tr></table></figure>
<ul>
<li>输出类似下面</li>
</ul>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">这个函数会对输入的两个数字进行相加运算...</span><br><span class="line">输入第一个数字: </span><br><span class="line">1</span><br><span class="line">输入第二个数字: </span><br><span class="line">2</span><br><span class="line">两个数字分别为 1 和 2 !</span><br><span class="line">输入的两个数字之和为 3 !</span><br></pre></td></tr></table></figure>
<ul>
<li>注意：<strong>所有函数在使用前必须定义</strong>。这意味着必须将函数放在脚本开始部分，直至shell解释器首次发现它时，才可以使用。调用函数仅使用其函数名即可。</li>
</ul>
<p><strong>函数参数</strong></p>
<ul>
<li>在Shell中，调用函数时可以向其传递参数。在函数体内部，通过 <code>$n</code> 的形式来获取参数的值，例如，<code>$1</code>表示第一个参数，<code>$2</code>表示第二个参数..</li>
</ul>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="meta">#!/bin/bash</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="title">funWithParam</span></span>()&#123;</span><br><span class="line">    <span class="built_in">echo</span> <span class="string">"第一个参数为 <span class="variable">$1</span> !"</span></span><br><span class="line">    <span class="built_in">echo</span> <span class="string">"第二个参数为 <span class="variable">$2</span> !"</span></span><br><span class="line">    <span class="built_in">echo</span> <span class="string">"第十个参数为 <span class="variable">$10</span> !"</span></span><br><span class="line">    <span class="built_in">echo</span> <span class="string">"第十个参数为 <span class="variable">$&#123;10&#125;</span> !"</span></span><br><span class="line">    <span class="built_in">echo</span> <span class="string">"第十一个参数为 <span class="variable">$&#123;11&#125;</span> !"</span></span><br><span class="line">    <span class="built_in">echo</span> <span class="string">"参数总数有 <span class="variable">$#</span> 个!"</span></span><br><span class="line">    <span class="built_in">echo</span> <span class="string">"作为一个字符串输出所有参数 $* !"</span></span><br><span class="line">&#125;</span><br><span class="line">funWithParam 1 2 3 4 5 6 7 8 9 34 73</span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">第一个参数为 1 !</span><br><span class="line">第二个参数为 2 !</span><br><span class="line">第十个参数为 10 !</span><br><span class="line">第十个参数为 34 !</span><br><span class="line">第十一个参数为 73 !</span><br><span class="line">参数总数有 11 个!</span><br><span class="line">作为一个字符串输出所有参数 1 2 3 4 5 6 7 8 9 34 73 !</span><br></pre></td></tr></table></figure>

      </div>
    
  </div>

</article>

<button class="assist-btn2 circle" id="assist_btn2" title="点亮屏幕" style="left: 27px; top: 152px;">
  <i class="iconfont" style="display:inline-block;color:red;width:20px;height:20px;">&#xe61d;</i>
</button>
<button class="assist-btn1 circle" id="assist_btn1" title="关闭屏幕亮度" style="left: 27px; top: 152px;">
  <i class="iconfont toc-title" style="display:inline-block;color:red;width:20px;height:20px;">&#xe61d;</i>
</button>


<script src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>	

<script src="https://my.openwrite.cn/js/readmore.js" type="text/javascript"></script>
<script>
  const btw = new BTWPlugin();
  btw.init({
    id: "container",
    blogId: "22699-1592137983091-414",
    name: "前端进阶之旅",
    qrcode: "https://poetries1.gitee.io/img-repo/2020/06/qrcode.jpg",
    keyword: "3a3b3c",
  });
</script>

<script type="text/javascript">

// white theme
var body = {color: "#555", background: "#000"};
var a_tag = {color: "#222"};
var header = { background: "#222"};
var logo_line_i = {background: "#222"};
// var post_code = {background: "#eee", color: "#222"};

function switch_theme() {
 $("body").css(body);
 $("a:not('.links-of-author-item a, .site-state-item a, .site-state-posts a, .feed-link a, .motion-element a, .post-tags a, .show-commit-cls a, #donate_board a')").css(a_tag);
 $(".header, .footer").css(header);
 $(".logo-line-before i, .logo-line-after i").css(logo_line_i);
 //$(".post code").css(post_code);
 $("#idhyt-surprise-ball #idhyt-surprise-ball-animation .drag").css(a_tag);
 $(".post-title-link, .posts-expand .post-meta, .post-comments-count, .disqus-comment-count, .post-category a, .post-nav-next a, .post-nav-item a").css(a_tag);
 
 // $("code").css({color: '#c5c8c6', background: '#1d1f21'});
 //$("#assist_btn1").hide(1500);
}

$(function () {
$("#assist_btn2").css("display","none");
 $("#assist_btn1").click(function() {
     switch_theme();
$("div#toc.toc-article").css({
 "background":"#eaeaea",
 "opacity":1
});
$(".toc-article ol").show();
$("#toc.toc-article .toc-title").css("color","#a98602");
$("#assist_btn1").css("display","none");
$("#assist_btn2").css("display","block");
 });
$("#assist_btn2").click(function() {
$("#assist_btn2").css("display","none");
$("#assist_btn1").css("display","block");
$("body").css("background","url(http://www.miaov.com/static/ie/images/news/bg.png)")
     $(".header, .footer").css("background","url(http://www.miaov.com/static/ie/images/news/bg.png)")
$(".toc-article ol").toggle(1000);
 });
});


//背景随机

var Y, O, E, L, B, C, T, z, N, S, A, I;
!function() {
var e = function() {
for (O.clearRect(0, 0, L, B), T = [{
x: 0,
y: .7 * B + C
}, {
x: 0,
y: .7 * B - C
}]; T[1].x < L + C;) t(T[0], T[1])
}, t = function(e, t) {
O.beginPath(), O.moveTo(e.x, e.y), O.lineTo(t.x, t.y);
var n = t.x + (2 * I() - .25) * C,
 r = a(t.y);
O.lineTo(n, r), O.closePath(), N -= S / -50, O.fillStyle = "#" + (127 * A(N) + 128 << 16 | 127 * A(N + S / 3) + 128 << 8 | 127 * A(N + S / 3 * 2) + 128).toString(16), O.fill(), T[0] = T[1], T[1] = {
 x: n,
 y: r
}
}, a = function n(e) {
var t = e + (2 * I() - 1.1) * C;
return t > B || t < 0 ? n(e) : t
};
Y = document.getElementById("evanyou"), O = Y.getContext("2d"), E = window.devicePixelRatio || 1, L = window.innerWidth, B = window.innerHeight, C = 90, z = Math, N = 0, S = 2 * z.PI, A = z.cos, I = z.random, Y.width = L * E, Y.height = B * E, O.scale(E, E), O.globalAlpha = .6, document.onclick = e, document.ontouchstart = e, e()
}()

   
$("#toc-eye").click(function(){
$("#toc.toc-article").toggle(1000);
});

</script>


   
  <div class="text-center donation">
    <div class="inner-donation">
      <span class="btn-donation">支持一下</span>
      <div class="donation-body">
        <div class="tip text-center">扫一扫，支持poetries</div>
        <ul>
        
          <li class="item">
            
              <span>微信扫一扫</span>
            
            <img src="/images/weixin.jpg" alt="">
          </li>
        
          <li class="item">
            
              <span>支付宝扫一扫</span>
            
            <img src="/images/zhifubao.jpg" alt="">
          </li>
        
        </ul>
      </div>
    </div>
  </div>


   
  <div class="box-prev-next clearfix">
    <a class="show pull-left" href="/2018/12/23/express/">
        <i class="icon icon-angle-left"></i>
    </a>
    <a class="show pull-right" href="/2018/12/29/ts-intro-and-use-in-react/">
        <i class="icon icon-angle-right"></i>
    </a>
  </div>




</div>


  <a id="backTop" class="back-top">
    <i class="icon-angle-up"></i>
  </a>




  <div class="modal" id="modal">
  <span id="cover" class="cover hide"></span>
  <div id="modal-dialog" class="modal-dialog hide-dialog">
    <div class="modal-header">
      <span id="close" class="btn-close">关闭</span>
    </div>
    <hr>
    <div class="modal-body">
      <ul class="list-toolbox">
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/archives/"
              rel="noopener noreferrer"
              target="_self"
              >
              博客
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/categories/"
              rel="noopener noreferrer"
              target="_self"
              >
              分类
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/tags/"
              rel="noopener noreferrer"
              target="_self"
              >
              标签
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/search/"
              rel="noopener noreferrer"
              target="_self"
              >
              搜索
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/link/"
              rel="noopener noreferrer"
              target="_self"
              >
              友链
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/about/"
              rel="noopener noreferrer"
              target="_self"
              >
              关于
            </a>
          </li>
        
      </ul>

    </div>
  </div>
</div>



  
      <div class="fexo-comments comments-post">
    

    

    
    

    

    
    

    

<!-- Gitalk评论插件通用代码 -->
<div id="gitalk-container"></div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.css">
<script src="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js"></script>
<script>
const gitalk = new Gitalk({
  clientID: '5567a2c4abb858009d96',
  clientSecret: 'b9039ec056cf5c2346b3cdb63308a28c163f91e5',
  repo: 'poetries.github.io',
  owner: 'poetries',
  // 在这里设置一下截取前50个字符串, 这是因为 github 对 label 的长度有了要求, 如果超过
  // 50个字符串则会报错.
  // id: location.pathname.split('/').pop().substring(0, 49),
  id: location.pathname,
  admin: ['poetries'],
  // facebook-like distraction free mode
  distractionFreeMode: false
})
gitalk.render('gitalk-container')
</script>
<!-- Gitalk代码结束 -->



  </div>

  

  <script type="text/javascript">
  function loadScript(url, callback) {
    var script = document.createElement('script')
    script.type = 'text/javascript';

    if (script.readyState) { //IE
      script.onreadystatechange = function() {
        if (script.readyState == 'loaded' ||
          script.readyState == 'complete') {
          script.onreadystatechange = null;
          callback();
        }
      };
    } else { //Others
      script.onload = function() {
        callback();
      };
    }

    script.src = url;
    document.getElementsByTagName('head')[0].appendChild(script);
  }

  window.onload = function() {
    loadScript('/js/bundle.js?235683', function() {
      // load success
    });
  }
</script>


  <!-- 页面点击小红心 -->
  <script type="text/javascript" src="/js/clicklove.js"></script>
 
  
</body>
</html>
